package com.xintonghua.bussiness.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.xintonghua.base.utils.MyUtils;
import com.xintonghua.bussiness.R;
import com.xintonghua.bussiness.adapter.FriendAdapter;
import com.xintonghua.bussiness.api.HttpCent;
import com.xintonghua.bussiness.api.myinterface.DataCallBack;
import com.xintonghua.bussiness.base.BaseFragment;
import com.xintonghua.bussiness.bean.Contant;
import com.xintonghua.bussiness.bean.MyMemberBean;
import com.xintonghua.bussiness.ui.CustomerActivity;
import com.xintonghua.bussiness.ui.fragment.client.AddCustomersActivity;
import com.xintonghua.bussiness.ui.fragment.client.BirthuserActivity;
import com.xintonghua.bussiness.ui.fragment.client.ClientKindActivity;
import com.xintonghua.bussiness.ui.fragment.client.CustomersActivity;
import com.xintonghua.bussiness.ui.fragment.client.CustomersListActivity;
import com.xintonghua.bussiness.ui.fragment.client.WarningFileActivity;
import com.xintonghua.bussiness.ui.fragment.client.search.SearchActivity;
import com.xintonghua.bussiness.util.JsonUtil;
import com.xintonghua.bussiness.util.JumpUtils;
import com.xintonghua.bussiness.util.MyState;
import com.xintonghua.bussiness.util.PingYinHelper;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 我的客户
 * 作者：wanxianyi
 * 时间：2018/1/11.
 * 包名：com.xintonghua.bussiness.ui.fragment
 */

public class ClientFragment extends BaseFragment implements DataCallBack, MyUserList {
    @BindView(R.id.tv_birthuser)
    TextView tvBirthuser;
    @BindView(R.id.tv_warning_file)
    TextView tvWarningFile;
    @BindView(R.id.tv_customer_profile)
    TextView tvCustomerProfile;
    @BindView(R.id.tv_customers)
    TextView tvCustomers;
    @BindView(R.id.lv_user)
    ListView lvUser;
    @BindView(R.id.iv_add_member)
    ImageView ivAddMember;


    Unbinder unbinder;

    private PinyinComparator pinyinComparator;

    @Override
    public int getLayout() {
        return R.layout.fragment_client;
    }

    FriendAdapter adapter;
    BroadcastReceiver receiver;

    @Override
    public void initUI(View rootView) {
        unbinder = ButterKnife.bind(this, rootView);

        pinyinComparator = new PinyinComparator();
        List<Contant> contantList = new ArrayList<>();
        List<Contant> friends = setData();
        Collections.sort(friends, pinyinComparator);
        contantList.addAll(friends);
        adapter = new FriendAdapter(getActivity(), contantList);
        lvUser.setAdapter(adapter);
        lvUser.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                JumpUtils.jumpto(getActivity(), CustomerActivity.class, (Serializable) adapter.getItem(i));
            }
        });
        adapter.notifyDataSetChanged();

        getActivity().registerReceiver(receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    getList();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new IntentFilter(MyState.BROAD_CASET_RECEIVER_REFRESH_CLIENT));


        getList();
        ivAddMember.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                JumpUtils.jumpto(getActivity(), AddCustomersActivity.class, null);
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            if (receiver != null) {
                getActivity().unregisterReceiver(receiver);
                receiver = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        unbinder.unbind();
    }

    @OnClick({R.id.tv_birthuser, R.id.tv_warning_file, R.id.tv_customer_profile, R.id.tv_customers, R.id.et_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_birthuser:
                MyUtils.openActivity(getActivity(), BirthuserActivity.class);
                break;
            case R.id.tv_warning_file:
                MyUtils.openActivity(getActivity(), WarningFileActivity.class);
                break;
            case R.id.tv_customer_profile:
                MyUtils.openActivity(getActivity(), ClientKindActivity.class);
                break;
            case R.id.tv_customers:
                MyUtils.openActivity(getActivity(), CustomersListActivity.class);
                break;
            case R.id.et_search:
                MyUtils.openActivity(getActivity(), SearchActivity.class);
                break;
        }
    }

    private List<Contant> setData() {
        List<Contant> mContantList = new ArrayList<>();
        List<Contant> friends = new ArrayList<>();
        for (int i = 0; i < mContantList.size(); i++) {
            String pinyin;
            Contant friend = mContantList.get(i);
            pinyin = PingYinHelper.getPingYin(friend.getNickname());
            String letter = pinyin.substring(0, 1).toUpperCase();
            if (letter.matches("[A-Z]")) {
                friend.setPinYinName(letter);
            } else {
                friend.setPinYinName("#");
            }
            friends.add(friend);
        }
        return friends;
    }

    private List<Contant> setData(List<MyMemberBean> list) {
        List<Contant> mContantList = new ArrayList<>();
        mContantList = MyUserBeanArrayToContantArray(list);
        List<Contant> friends = new ArrayList<>();
        for (int i = 0; i < mContantList.size(); i++) {
            String pinyin;
            Contant friend = mContantList.get(i);
            pinyin = PingYinHelper.getPingYin(friend.getNickname());
            String letter = pinyin.substring(0, 1).toUpperCase();
            if (letter.matches("[A-Z]")) {
                friend.setPinYinName(letter);
            } else {
                friend.setPinYinName("#");
            }
            friends.add(friend);
        }
        return friends;
    }

    @Override
    public void dataBack(Object data, int order) {
        super.dataBack(data, order);
        switch (order) {
            case MyState.requestL3000:
                try {
                    List<MyMemberBean> list = (List<MyMemberBean>) JsonUtil.getListByJsonString(data.toString(), MyMemberBean.class);
                    List<Contant> contantList = new ArrayList<>();
                    List<Contant> friends = setData(list);
                    Collections.sort(friends, pinyinComparator);
                    contantList.addAll(friends);
//                    FriendAdapter adapter = new FriendAdapter(getActivity(), contantList);
                    adapter.setList(contantList);
                    adapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
        }
    }

    @Override
    public void getList() {
        //Log.i("aaa", "etSearch" + etSearch);
        //String searchName = etSearch.getText().toString().trim();
        HttpCent.getInstance(getActivity()).getMyUserList("", ClientFragment.this, MyState.requestL3000);
    }

    @Override
    public List<Contant> MyUserBeanArrayToContantArray(List<MyMemberBean> MyUserlistBean) {

        List<Contant> contlist = new ArrayList<>();
        for (int i = 0; i < MyUserlistBean.size(); i++) {
            Contant contant = new Contant(MyUserlistBean.get(i).getUsername());
            contant.setFirstPY(MyUserlistBean.get(i).getFirstPY());
            contant.setNickname(MyUserlistBean.get(i).getNickname());
            contant.setPhone(MyUserlistBean.get(i).getPhone());
            contant.setId(MyUserlistBean.get(i).getId());
            contlist.add(contant);
        }


        return contlist;
    }

    /**
     * 拼音首字母排序
     */
    public class PinyinComparator implements Comparator<Contant> {
        public int compare(Contant o1, Contant o2) {
            String str1 = getPingYin(o1.getNickname());
            String str2 = getPingYin(o2.getNickname());
            int flag = str1.compareTo(str2);
            return flag;
        }

        /**
         * 将字符串中的中文转化为拼音,其他字符不变
         *
         * @param inputString
         * @return
         */
        private String getPingYin(String inputString) {
            HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
            format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
            format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
            format.setVCharType(HanyuPinyinVCharType.WITH_V);

            char[] input = inputString.trim().toCharArray();// 把字符串转化成字符数组
            String output = "";

            try {
                for (int i = 0; i < input.length; i++) {
                    // \\u4E00是unicode编码，判断是不是中文
                    if (java.lang.Character.toString(input[i]).matches(
                            "[\\u4E00-\\u9FA5]+")) {
                        // 将汉语拼音的全拼存到temp数组
                        String[] temp = PinyinHelper.toHanyuPinyinStringArray(
                                input[i], format);
                        // 取拼音的第一个读音
                        output += temp[0];
                    }
                    // 大写字母转化成小写字母
                    else if (input[i] > 'A' && input[i] < 'Z') {
                        output += java.lang.Character.toString(input[i]);
                        output = output.toLowerCase();
                    }
                    output += java.lang.Character.toString(input[i]);
                }
            } catch (Exception e) {
            }
            return output;
        }
    }

}

interface MyUserList {
    //获取用户的列表
    void getList();

    //List<MyMemberBean> 转 List<Contant>
    List<Contant> MyUserBeanArrayToContantArray(List<MyMemberBean> MyUserlistBean);
}